#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
U盘音乐文件扫描器
扫描SANDISK U盘中的音乐文件并输出到text文件
"""

import os
import glob
from pathlib import Path

class MusicScanner:
    def __init__(self, usb_path="/Volumes/SANDISK"):
        """初始化音乐扫描器"""
        self.usb_path = usb_path
        self.output_dir = "text"
        self.music_extensions = ['.mp3', '.wav', '.flac', '.m4a', '.aac', '.ogg', '.wma']
        
        # 确保输出目录存在
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
    
    def scan_music_files(self):
        """扫描U盘中的音乐文件"""
        print(f"🔍 开始扫描U盘: {self.usb_path}")
        
        if not os.path.exists(self.usb_path):
            print(f"❌ U盘路径不存在: {self.usb_path}")
            return []
        
        music_files = []
        
        # 递归扫描所有目录
        for root, dirs, files in os.walk(self.usb_path):
            for file in files:
                # 跳过隐藏文件和系统文件
                if file.startswith('.') or file.startswith('._'):
                    continue
                
                file_path = os.path.join(root, file)
                file_ext = os.path.splitext(file)[1].lower()
                
                if file_ext in self.music_extensions:
                    # 获取相对于U盘根目录的路径
                    relative_path = os.path.relpath(file_path, self.usb_path)
                    music_files.append({
                        'name': file,
                        'path': relative_path,
                        'full_path': file_path,
                        'size': os.path.getsize(file_path)
                    })
        
        print(f"✅ 扫描完成，找到 {len(music_files)} 个音乐文件")
        return music_files
    
    def clean_filename(self, filename):
        """清理文件名，移除扩展名和特殊字符"""
        # 移除扩展名
        name = os.path.splitext(filename)[0]
        
        # 过滤掉以._开头的隐藏文件
        if name.startswith('._'):
            return None
        
        # 移除一些常见的编号前缀
        import re
        name = re.sub(r'^\d+[\.\-\s]*', '', name)  # 移除开头的数字编号
        name = re.sub(r'^\[\d+\]', '', name)       # 移除 [01] 这样的编号
        
        return name.strip()
    
    def generate_music_list(self, music_files):
        """生成音乐名称列表并保存到文件"""
        if not music_files:
            print("❌ 没有找到音乐文件")
            return
        
        # 提取音乐名称并去重
        music_names = []
        seen_names = set()
        
        for music_file in music_files:
            clean_name = self.clean_filename(music_file['name'])
            if clean_name and clean_name not in seen_names:
                music_names.append(clean_name)
                seen_names.add(clean_name)
        
        # 排序
        music_names.sort()
        
        # 生成编号列表
        numbered_list = []
        for i, name in enumerate(music_names, 1):
            numbered_list.append(f"音乐{i}、{name}")
        
        # 保存到文件
        output_file = os.path.join(self.output_dir, "music_list.txt")
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("SANDISK U盘音乐文件统计\n")
            f.write("=" * 50 + "\n\n")
            f.write(f"扫描时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"总计: {len(music_names)} 首音乐\n\n")
            
            for item in numbered_list:
                f.write(item + "\n")
        
        print(f"📄 音乐列表已保存到: {output_file}")
        print(f"📊 总计: {len(music_names)} 首音乐")
        
        # 同时生成一个详细报告
        self.generate_detailed_report(music_files)
        
        return numbered_list
    
    def generate_detailed_report(self, music_files):
        """生成详细报告"""
        output_file = os.path.join(self.output_dir, "detailed_report.txt")
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("SANDISK U盘音乐文件详细报告\n")
            f.write("=" * 50 + "\n\n")
            f.write(f"扫描路径: {self.usb_path}\n")
            f.write(f"总文件数: {len(music_files)}\n")
            f.write(f"扫描时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            
            # 按文件夹分组
            folders = {}
            for music_file in music_files:
                folder = os.path.dirname(music_file['path'])
                if not folder:
                    folder = "根目录"
                
                if folder not in folders:
                    folders[folder] = []
                folders[folder].append(music_file)
            
            # 输出每个文件夹的内容
            for folder, files in sorted(folders.items()):
                f.write(f"📁 {folder} ({len(files)} 个文件)\n")
                f.write("-" * 30 + "\n")
                
                for music_file in sorted(files, key=lambda x: x['name']):
                    size_mb = music_file['size'] / (1024 * 1024)
                    f.write(f"  🎵 {music_file['name']} ({size_mb:.1f}MB)\n")
                
                f.write("\n")
        
        print(f"📄 详细报告已保存到: {output_file}")
    
    def run(self):
        """运行扫描器"""
        print("🎵 U盘音乐文件扫描器")
        print("=" * 30)
        
        # 扫描音乐文件
        music_files = self.scan_music_files()
        
        if music_files:
            # 生成音乐列表
            music_list = self.generate_music_list(music_files)
            
            # 显示前10个作为预览
            print("\n📋 音乐列表预览（前10首）:")
            for item in music_list[:10]:
                print(f"  {item}")
            
            if len(music_list) > 10:
                print(f"  ... 还有 {len(music_list) - 10} 首")
        else:
            print("❌ 未找到任何音乐文件")

def main():
    """主函数"""
    scanner = MusicScanner()
    scanner.run()

if __name__ == "__main__":
    main() 